package com.guli.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guli.member.dao.MemberLevelDao;
import com.guli.member.entity.MemberLevelEntity;
import com.guli.common.exception.RegisterException;
import com.guli.member.utils.HttpUtils;
import com.guli.member.vo.MemberLoginVo;
import com.guli.common.vo.MemberRegistVo;
import com.guli.member.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.member.dao.MemberDao;
import com.guli.member.entity.MemberEntity;
import com.guli.member.service.MemberService;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) {
        //检验用户名或密码是否唯一
        String phone = memberRegistVo.getPhone();
        Integer integer = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (integer != null && integer > 0) {
            throw new RegisterException("手机号码已存在");
        }
        String userName = memberRegistVo.getUserName();
        Integer integer1 = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (integer1 != null && integer1 > 0) {
            throw new RegisterException("用户名已存在");
        }
        //查询默认会员等级
        MemberLevelEntity memberLevel = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        //获取会员等级id
        Long memberLevelId = memberLevel.getId();
        //设置member
        MemberEntity member = new MemberEntity();
        member.setLevelId(memberLevelId);
        member.setMobile(phone);
        member.setUsername(userName);
        member.setNickname("用户" + UUID.randomUUID().toString().replace("-", "").substring(0, 5));
        //密码需加密存储 BCryptPasswordEncoder加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegistVo.getPassword());
        member.setPassword(encode);
        this.baseMapper.insert(member);
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            return "redirect:http://gulimall.com";
        }
        return "login";
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        //获取账号和密码
        String loginacct = memberLoginVo.getLoginacct();
        String password = memberLoginVo.getPassword();
        //数据库查询
        //查询是否有该用户名或手机号
        MemberEntity member = this.baseMapper
                .selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                        .or().eq("mobile", loginacct));
        if (member == null) {
            //登录失败
            return null;
        }
        //获取数据库的password
        String password1 = member.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(password, password1);
        if (!matches) {
            //登录失败
            return null;
        }
        //登录成功
        return member;
    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) {
        String uid = socialUser.getUid();
        MemberEntity member = this.baseMapper
                .selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (member != null) {
            //这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(member.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);
            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());
            return member;
        } else {
            //没有查到当前社交用户对应的记录需要注册一个
            MemberEntity register = new MemberEntity();
            //查询当前社交用户的社交账号信息(昵称，性别)
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            try {
                //获取用户微博基本信息 通过access_token和uid进行获取
                HttpResponse response = HttpUtils
                        .doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println("response = " + response);
                    String users = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(users);
                    //获取昵称
                    String name = jsonObject.getString("name");
                    //获取性别
                    String gender = jsonObject.getString("gender");
                    //获取所在地
                    String location = jsonObject.getString("location");
                    String description = jsonObject.getString("description");
                    register.setCity(location);
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setSign(description);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(register);
            return register;
        }
    }

}